"""
Base Interface Class

定义雷达通信接口的抽象基类
"""

from abc import ABC, abstractmethod
from typing import Optional, Callable, Any
from ..exceptions import RadarConnectionError, RadarTimeoutError


class RadarInterface(ABC):
    """雷达通信接口抽象基类"""

    def __init__(self, config: dict):
        self.config = config
        self.is_connected = False
        self.timeout = config.get('timeout', 1000)
        self.retry_count = config.get('retry_count', 3)
        self._data_callback: Optional[Callable[[bytes], None]] = None

    @abstractmethod
    def connect(self) -> None:
        """连接到雷达设备"""
        pass

    @abstractmethod
    def disconnect(self) -> None:
        """断开与雷达设备的连接"""
        pass

    @abstractmethod
    def send_data(self, data: bytes) -> None:
        """发送数据到雷达设备"""
        pass

    @abstractmethod
    def receive_data(self, timeout: Optional[int] = None) -> bytes:
        """从雷达设备接收数据"""
        pass

    @abstractmethod
    def send_command(self, command: bytes, timeout: Optional[int] = None) -> bytes:
        """发送命令并等待响应"""
        pass

    def set_data_callback(self, callback: Callable[[bytes], None]) -> None:
        """设置数据接收回调函数"""
        self._data_callback = callback

    def _handle_received_data(self, data: bytes) -> None:
        """处理接收到的数据"""
        if self._data_callback:
            self._data_callback(data)

    def _retry_operation(self, operation, *args, **kwargs):
        """重试机制"""
        last_error = None
        for attempt in range(self.retry_count):
            try:
                return operation(*args, **kwargs)
            except Exception as e:
                last_error = e
                if attempt == self.retry_count - 1:
                    raise last_error

    def __enter__(self):
        """上下文管理器支持"""
        self.connect()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """上下文管理器支持"""
        self.disconnect()